/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.axiom.persistence;

import com.axiom.vo.user_detail;
import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author Shuhail
 */
public class user_detail_persist {
    
    Session sess = null;
    Transaction tx = null;
    
    public static user_detail_persist getInstance() {
        
        return new user_detail_persist();
        
           }
    
    public user_detail_persist() {
        
         SessionFactory sf = new Configuration().configure(new File("src/hibernate.cfg.xml")).buildSessionFactory();
         sess = sf.openSession();
         tx = sess.beginTransaction();
         
         
        
    }
    
    public user_detail fetchForAuthentication(String name) {
        
        try {
            
            Query query = sess.getNamedQuery("getUserCredentials");
            query.setString("user_name", name);
            List results = query.list();
            if(results.size()==0) {
                
                System.out.println("Not A Valid User");
                return null;
            }
            Iterator it = results.iterator();
            while(it.hasNext()) {
                user_detail detail = (user_detail)it.next();
                return detail;
            }
           
        }
         catch(Exception e) {
                
                return null;
            }
        return null;
    }
    
    
    public boolean insertFresh(user_detail userDetails) {
        try {
        sess.save(userDetails);
        tx.commit();
        }catch(Exception e) {
            
            return false;
        }
        return true;
    }
    
    public static void main(String[] args) {
        
        user_detail detail = new user_detail();
        detail.setDate(new Date());
        detail.setName("shukad33");
        detail.setPass("12344");
        detail.setRole("ADMIN");
        detail.setUser_id("shukad");
        
        user_detail_persist user = new user_detail_persist();
       // user.insertFresh(detail);
        user_detail det = user.fetchForAuthentication("shuhhhh");
        System.out.println(det.getName()+"---"+det.getPass());
    }
}
